﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Akka.Ext.Http.Mvc
{
    public static class AkkaHttpMvcMap
    {
        public static void MapAkkaHttp(this IApplicationBuilder app, string startPath, AkkaHttpClient client, Func<RequestInfo, HttpRequest, string> onBefore, Action<ResponseInfo, HttpResponse> onAfter = null)
        {
            app.MapWhen(context =>
            {
                return context.Request.Path.StartsWithSegments(startPath);

            }, builder =>
            {
                builder.Run(async (httpcontext) =>
                {
                    try
                    {
                        var req = new RequestInfo();
                        string actorPath = onBefore(req, httpcontext.Request);
                        if (!string.IsNullOrEmpty(actorPath))
                        {
                            await CommonUtils.CreateRequestInfo(httpcontext.Request, req);
                            var res = await client.ExecuteAsync(actorPath, req);
                            await CommonUtils.CreateResponseInfo(httpcontext.Response, res);
                            onAfter?.Invoke(res, httpcontext.Response);
                        }
                        else
                        {
                            var res = new ResponseInfo { Code = -1, IsSuccess = false, ErrorMessage = "actorPath is null or empty" };
                            onAfter?.Invoke(res, httpcontext.Response);
                        }
                    }
                    catch (Exception ex)
                    {
                        var res = new ResponseInfo { Code = -1, IsSuccess = false, ErrorMessage = ex.Message };
                        onAfter?.Invoke(res, httpcontext.Response);
                    }

                });
            });
        }

    }
}
